package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.HistorySearchDto;
import com.heima.search.mongoPojo.ApUserSearch;
import com.heima.search.service.ApUserSearchService;
import com.heima.utils.common.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ApUserSearchServiceImpl implements ApUserSearchService {

    @Autowired
    private MongoTemplate mongoTemplate;

    // 保存用户搜索记录到mongodb（最多10条）
    @Async
    @Override
    public void insertToMongo(Integer userId, String keyword) {

        log.info("保存用户搜索记录到mongodb:"+ keyword+ userId);
        //参数校验
        if (userId == null || keyword == null){
            return;
        }
        //记录是否存在
        ApUserSearch apUserSearch = mongoTemplate.findOne(new Query(Criteria.where("userId").is(userId).and("keyword").is( keyword)), ApUserSearch.class);
        log.info("记录是否存在:"+ apUserSearch);
        if (apUserSearch != null){
            apUserSearch.setCreatedTime(new Date());
            ApUserSearch saved = mongoTemplate.save(apUserSearch);
            log.info("保存结果不存在记录:"+ saved);
            return;
        }
        //记录是否达到10条
        long count = mongoTemplate.count(new Query(Criteria.where("userId").is(userId)), ApUserSearch.class);
        log.info("记录是否达到10条:"+ count);
        if (count >= 10){
            List<ApUserSearch> apUserSearches = mongoTemplate.find(new Query(Criteria.where("userId").is(userId)).with(Sort.by(Sort.Direction.DESC, "createdTime")), ApUserSearch.class);
            ApUserSearch apUserSearch10 = apUserSearches.get(9);
            apUserSearch10.setKeyword(keyword);
            apUserSearch10.setCreatedTime(new Date());
            ApUserSearch save = mongoTemplate.save(apUserSearch10);
            log.info("保存结果替换:"+ save);
        }else {
            //保存
            ApUserSearch apUserSearchLt9 = new ApUserSearch();
            apUserSearchLt9.setUserId(userId);
            apUserSearchLt9.setKeyword(keyword);
            apUserSearchLt9.setCreatedTime(new Date());
            ApUserSearch apUserSearch1 = mongoTemplate.save(apUserSearchLt9);
            log.info("保存结果新增:"+ apUserSearch1);

        }

    }

    @Override
    public ResponseResult findUserSearch() {

        Integer userId = AppThreadLocalUtil.getUser().getId();
        List<ApUserSearch> apUserSearches = mongoTemplate.find(new Query(Criteria.where("userId").is(userId)), ApUserSearch.class);


        return ResponseResult.okResult(apUserSearches);
    }

    @Override
    public ResponseResult delUserSearch(HistorySearchDto dto) {

        if (dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //获取用户id
        Integer userId = AppThreadLocalUtil.getUser().getId();
        if (userId == null)
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);

        mongoTemplate.remove(new Query(Criteria.where("id").is(dto.getId()).and("userId").is(userId)), ApUserSearch.class);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
